package com.example.yam.greenapp;

import android.app.Dialog;
import android.app.FragmentManager;
import android.content.Intent;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DetailActivity extends AppCompatActivity {

    //常量
    private final String TAG="DetailActivity";

    //变量
    private String myurl = MyApplication.localhost+"Green/index.php/indexg/showgood/id/";
    private String id = null;

    public String det = null;
    public String gid = null;
    //控件
    private ImageView imageView = null;
    private TextView nameAlitro = null;
    private TextView price = null;
    private TextView sum = null;
    private TextView kucun = null;
    private Button jian = null;
    private EditText num = null;
    private Button add = null;
    private Button shopcar = null;//添加到购物车
    private Button det_buy = null;//立即购买

    private TextView guide_intro = null;
    private TextView guide_plist = null;

    //Fragment
    private det_introFragment det_intro_fragment;//详细介绍
    private det_plistFragment det_plist_fragment;//评论列表

    //当前购物车的Adapter
    DialogGoodsAdapter dialogGoodsAdapter ;

    //当前商品信息
    DGoods dgood;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        //工具栏--返回
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        init();
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
   public void  init(){//实例化控件
        this.imageView = (ImageView) super.findViewById(R.id.det_pic);
        this.nameAlitro = (TextView) super.findViewById(R.id.det_nameLitro);
        this.price = (TextView) super.findViewById(R.id.det_price);
        this.sum = (TextView) super.findViewById(R.id.det_sum);
        this.kucun = (TextView) super.findViewById(R.id.det_kucun);
        this.jian = (Button) super.findViewById(R.id.det_jian);
        this.num = (EditText) super.findViewById(R.id.det_num);
        this.add = (Button) super.findViewById(R.id.det_add);
        this.shopcar = (Button) super.findViewById(R.id.det_shopcar);
        this.det_buy = (Button) super.findViewById(R.id.det_buy);

       //添加监听
       this.jian.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View v) {
               int Nnum = Integer.parseInt(DetailActivity.this.num.getText().toString());//转换成数字
               if(Nnum==1) return;
               Nnum--;
               DetailActivity.this.num.setText(""+Nnum);
           }
       });
       this.add.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View v) {
               int Nnum = Integer.parseInt(DetailActivity.this.num.getText().toString());//转换成数字
               Nnum++;
               DetailActivity.this.num.setText(""+Nnum);
           }
       });
       this.shopcar.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View v) {
               DetailActivity.this.showDialog();
           }
       });
       this.guide_intro = (TextView) super.findViewById(R.id.det_guide_intro);
       this.guide_intro.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View v) {
                initFragment_intro();
           }
       });
       this.guide_plist = (TextView) super.findViewById(R.id.det_guide_pinglun);
       this.guide_plist.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View v) {
               initFragment_plist();
           }
       });
       this.det_buy.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View v) {
               DetailActivity.this.shdz();
           }
       });
       //设置数据
       Intent it = getIntent();
       this.id = it.getStringExtra("id");
       Log.v(TAG,"id是"+this.id);
       String nurl = this.myurl+this.id;
       VolleyGetString(nurl);
    }
    //使用volley获取数据
    private void VolleyGetString(String url){
        RequestQueue mQueue = MyApplication.getHttpQueue();
        Log.d(TAG, "开始了");
        StringRequest stringRequest = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {//正确搜索到数据
                        parseJSONobject(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, error.getMessage(), error);
            }
        });
        mQueue.add(stringRequest);
    }
    //json解析
    private void parseJSONobject(String ss){
        try{
             Log.d(TAG,"数据是"+ss);
            JSONObject jsb = new JSONObject(ss);
            JSONArray jab = (JSONArray) new JSONArray(jsb.getString("goods"));
            JSONObject jb=jab.getJSONObject(0);
            ImageLoader mImageLoader= MyApplication.getmImageLoader();
            String pic = MyApplication.localhost+"Green/public/photo/"+jb.getString("pic");
            mImageLoader.get(pic.replace("thumb_",""),
                    ImageLoader.getImageListener(this.imageView,R.drawable.bicon, R.drawable.login));
            Log.v(TAG,"图片路径"+pic);
            this.nameAlitro.setText(jb.getString("name")+jb.getString("lintro"));
            this.price.setText(jb.getString("price")+"元/"+jb.getString("danwei"));
            this.sum.setText("已售出:"+jb.getString("sum"));
            this.kucun.setText("库存:"+jb.getString("kucun"));

            this.det = jb.getString("intro");
            this.gid = jb.getString("id");

            this.dgood = new DGoods(jb.getString("id"),pic, jb.getString("name"),jb.getString("danwei"), jb.getString("price"),
                    ""+1,jb.getString("price"),"0");
            Log.v(TAG,"dgood设置完成");
            initFragment_intro();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //隐藏所有的fragment
    private void hideFragment(android.app.FragmentTransaction transaction){
        if(DetailActivity.this.det_intro_fragment != null){
            transaction.hide(DetailActivity.this.det_intro_fragment);
        }
        if(DetailActivity.this.det_plist_fragment != null){
            transaction.hide(DetailActivity.this.det_plist_fragment);
        }
    }
    //商品详细界面
    public void initFragment_intro(){
        DetailActivity.this.changeColor(DetailActivity.this.guide_intro);
        FragmentManager fragmentManager =getFragmentManager();
        android.app.FragmentTransaction transaction = fragmentManager.beginTransaction();

        if(DetailActivity.this.det_intro_fragment == null){
            DetailActivity.this.det_intro_fragment = new det_introFragment();
            Bundle bundle = new Bundle();
            bundle.putString("det",this.det);
            DetailActivity.this.det_intro_fragment.setArguments(bundle);
            transaction.add(R.id.det_fg,DetailActivity.this.det_intro_fragment);
        }
        hideFragment(transaction);
        transaction.show(DetailActivity.this.det_intro_fragment);
        transaction.commit();
    }
    //评论列表
    public void initFragment_plist(){
        DetailActivity.this.changeColor(DetailActivity.this.guide_plist);
        FragmentManager fragmentManager =getFragmentManager();
        android.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (DetailActivity.this.det_plist_fragment == null) {
            DetailActivity.this.det_plist_fragment = new det_plistFragment();
            Bundle bundle = new Bundle();
            bundle.putString("gid",this.gid);
            DetailActivity.this.det_plist_fragment.setArguments(bundle);
            transaction.add(R.id.det_fg,DetailActivity.this.det_plist_fragment);
        }
        hideFragment(transaction);
        transaction.show(DetailActivity.this.det_plist_fragment);
        transaction.commit();
    }
    //修改本控件颜色为绿色
    public void changeColor(TextView tv){
        DetailActivity.this.guide_intro.setTextColor(DetailActivity.this.getResources()
                .getColor(R.color.color_tv_guide));
        DetailActivity.this.guide_plist.setTextColor(DetailActivity.this.getResources()
                .getColor(R.color.color_tv_guide));

        tv.setTextColor(DetailActivity.this.getResources().getColor(R.color.color_tv_guide_HighLight));//设置高亮
    }
    //显示dialog
    public void showDialog(){
        View view = LayoutInflater.from(DetailActivity.this).inflate(R.layout.nowshopcardialog,null);
        final Dialog dialog = new Dialog(this,R.style.common_dialog);
        dialog.setContentView(view);
        dialog.show();
        //控件设置
        ListView dialog_list = (ListView) view.findViewById(R.id.dialog_shopcar);
        Button dialog_cancel = (Button) view.findViewById(R.id.dialog_cancle);
        Button dialog_buy = (Button) view.findViewById(R.id.dialog_buy);

        //增加数据
        int nnnum=Integer.parseInt(this.num.getText().toString());
        this.dgood.setNum(""+nnnum);
        Log.v(TAG,""+nnnum);
        Log.v(TAG,""+dgood.getPrice().replace("元",""));
        float total = nnnum * Float.parseFloat(this.dgood.getPrice().replace("元",""));
        this.dgood.setTotal(String.valueOf(total));

        MyApplication.diaSum += total;
        //适配器
        this.dialogGoodsAdapter = new DialogGoodsAdapter(view.getContext(),R.layout.dialog_list,MyApplication.dialoggoodsList);
        MyApplication.dialoggoodsList.add(this.dgood);
        dialog_list.setAdapter(DetailActivity.this.dialogGoodsAdapter);

        //点击事件监听
        dialog_cancel.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog_buy.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                DetailActivity.this.shdz();
            }
        });

        // 设置相关位置，一定要在 show()之后--使用于http://blog.csdn.net/Beyond0525/article/details/46661147
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.BOTTOM;
        params.alpha=1.0f;
        window.setAttributes(params);
    }
    //选择收货地址
    public void shdz(){
        Intent it = new Intent(DetailActivity.this,ShdzActivity.class);
        startActivity(it);
    }
}
